package com.example.myapplication.widget;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myapplication.R;

import java.util.Calendar;

public class DatePickerActivity extends AppCompatActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener {

    private TextView tvDate;

    private DatePicker datePicker;

    private TextView tvDateFromDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_date_picker);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        findViewById(R.id.btn_date_ok).setOnClickListener(this);
        tvDate = findViewById(R.id.tv_date);
        datePicker = findViewById(R.id.date_picker);

        findViewById(R.id.btn_open_date_dlg).setOnClickListener(this);
        tvDateFromDialog = findViewById(R.id.tv_date_from_dlg);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_date_ok) {
            String desc = String.format("您选择的日期是：%d年%d月%d日", datePicker.getYear(), datePicker.getMonth() + 1, datePicker.getDayOfMonth());
            tvDate.setText(desc);
        } else if (v.getId() == R.id.btn_open_date_dlg) {
            // 通过日历对话框选择日期
            Calendar calendar = Calendar.getInstance();
            DatePickerDialog dialog = new DatePickerDialog(
                    this, this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DAY_OF_MONTH));
            dialog.show();
        }
    }

    /**
     * 日历对话框选择日期后的回调
     */
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        String desc = String.format("您选择的日期是：%d年%d月%d日", year, month + 1, dayOfMonth);
        tvDateFromDialog.setText(desc);
    }
}